package logic

import (
	"context"
	"errors"
	"goods/goodsrpc/goodsrpc"
	"goods/goodsrpc/internal/svc"
	"goods/models/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodAddLogic {
	return &GoodAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodAddLogic) GoodAdd(in *goodsrpc.GoodAddRequest) (*goodsrpc.GoodAddResponse, error) {
	// todo: add your logic here and delete this line

	class := mysql.Class{
		Name: in.ClassName,
	}
	mysql.DB.Debug().Where("name = ?", in.ClassName).FirstOrCreate(&class)

	if class.ID == 0 {
		return nil, errors.New("分类添加失败")
	}
	var goods mysql.Good
	mysql.DB.Debug().Where("goodName = ?", in.GoodName).Find(&goods)
	if goods.GoodName == "" {
		return nil, errors.New("商品已经存在请重新创建")
	}

	good := mysql.Good{
		GoodName: in.GoodName,
		Title:    in.Title,
		Image:    in.Image,
		ClassId:  int(class.ID),
	}
	mysql.DB.Debug().Create(&good)

	return &goodsrpc.GoodAddResponse{
		GoodId: int64(good.ID),
	}, nil
}
